<template>
  <div class="jobs">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-background">
        <el-carousel height="100%" indicator-position="outside" arrow="always" :autoplay="true" :interval="5000" :key="sixImagesKey">
          <el-carousel-item v-for="(img, idx) in sixImages" :key="idx">
            <img :src="img" alt="工作机会背景" class="header-bg-image" @click="handleHeaderImageClick(idx, img)" style="cursor: pointer;" />
          </el-carousel-item>
        </el-carousel>
        <div class="header-overlay"></div>
      </div>
      <div class="header-content">
        <h1>{{ $t('jobs.title') }}</h1>
        <p>{{ $t('jobs.subtitle') }}</p>
      </div>
    </div>

    <div class="filters-section">
      <div class="container">
        <div class="filters">
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索岗位、公司或地点"
              class="search-input"
              clearable
              size="large"
              @keyup.enter="handleSearch"
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button 
              type="primary" 
              @click="handleSearch" 
              class="search-btn" 
              size="large"
              :loading="loading"
              :disabled="loading"
            >
              {{ loading ? '搜索中...' : '搜索' }}
            </el-button>
          </div>
          <div class="search-tags">
            <span class="tag-label">热门搜索：</span>
            <el-tag 
              v-for="tag in hotTags" 
              :key="tag" 
              class="hot-tag"
              @click="searchKeyword = tag; handleSearch()"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>

    <!-- 工作列表 -->
    <div class="jobs-section">
      <div class="container">
        <div class="jobs-grid">
          <div 
            v-for="job in filteredJobs" 
            :key="job.positionId"
            class="job-card"
            @click="viewJobDetail(job)"
          >
            <!--<div class="job-image">-->
              <!--<img :src="job.image || job.jobImage || job.coverImage || '/src/assets/index/jobs-bg.jpg'" :alt="job.jobTitle || job.title" />-->
              <!--<div class="job-overlay">-->
                <!--<el-button type="primary" @click.stop="applyJob(job)">-->
                  <!--{{ $t('jobs.apply') }}-->
                <!--</el-button>-->
              <!--</div>-->
            <!--</div>-->
            
            <div class="job-info">
              <div class="job-header">
                <h3>{{ job.jobTitle || job.title }}</h3>
                <div class="job-company">
                  <!--<img :src="job.companyLogo || job.company?.logo" :alt="job.companyName || job.company?.name" class="company-logo" />-->
                  <span>{{ job.companyName || job.company?.name }}</span>
                </div>
              </div>
              
              <div class="job-details">
                <div class="job-location">
                  <el-icon><Location /></el-icon>
                  <span>{{ job.location || '地点待定' }}</span>
                </div>
                <div class="job-salary">
                  <el-icon><Money /></el-icon>
                  <span>{{ job.salary || job.expectedSalary || '薪资面议' }}</span>
                </div>
                <div class="job-experience">
                  <el-icon><User /></el-icon>
                  <span>{{ job.experience || job.experienceRequirement || '经验不限' }}</span>
                </div>
              </div>
              
              <div class="job-tags">
                <el-tag size="small" :type="getTagType(job.jobType || job.category)">
                  {{ job.jobType || job.category || '其他' }}
                </el-tag>
                <el-tag size="small" type="success" v-if="job.urgent">
                  急聘
                </el-tag>
                <el-tag size="small" type="warning" v-if="job.new">
                  新职位
                </el-tag>
              </div>
              
              <div class="job-description">
                <p>{{ job.jobDescription || job.description || '暂无描述' }}</p>
              </div>
              
              <div class="job-actions">
                <el-button type="primary" @click.stop="applyJob(job)">
                  {{ $t('jobs.apply') }}
                </el-button>
                <el-button @click.stop="viewJobDetail(job)">
                  {{ $t('jobs.view') }}
                </el-button>
                <el-button @click.stop="shareJobFromList(job)" type="info">
                  分享
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[12, 24, 36, 48]"
            :total="totalJobs"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 工作详情对话框 -->
    <el-dialog 
      v-model="jobDetailVisible" 
      :title="currentJob?.jobTitle || currentJob?.title"
      width="70%"
      :before-close="closeJobDetail"
    >
      <div v-if="currentJob" class="job-detail-content">
                  <div class="job-detail-header">
            <!--<img :src="currentJob.image || currentJob.jobImage || currentJob.coverImage || '/src/assets/index/jobs-bg.jpg'" :alt="currentJob.jobTitle || currentJob.title" class="job-detail-image" />-->
            <div class="job-detail-info">
              <!--<h2>{{ currentJob.jobTitle || currentJob.title }}</h2>-->
              <div class="company-info">
                <!--<img :src="currentJob.companyLogo || currentJob.company?.logo || '/src/assets/index/unnamed.png'" :alt="currentJob.companyName || currentJob.company?.name" class="company-logo-large" />-->
                <div>
                  <h4>{{ currentJob.companyName || currentJob.company?.name }}</h4>
                  <p>{{ currentJob.companyDescription || currentJob.company?.description || '暂无公司描述' }}</p>
                </div>
              </div>
            </div>
          </div>

          <!-- 分享者信息 -->
          <!--<div class="share-info-section" v-if="shareUser">-->
            <!--<h3>分享者信息</h3>-->
            <!--<div class="share-user-info">-->
              <!--<div class="share-user-avatar">-->
                <!--<el-icon><User /></el-icon>-->
              <!--</div>-->
              <!--<div class="share-user-details">-->
                <!--<h4>{{ shareUser.nickName || shareUser.userName }}</h4>-->
                <!--<p>{{ shareUser.userRole === 'admin' ? '管理员' : '业务员' }}</p>-->
                <!--<div class="share-user-contact">-->
                  <!--<span v-if="shareUser.phonenumber">-->
                    <!--<el-icon><Phone /></el-icon>-->
                    <!--{{ shareUser.phonenumber }}-->
                  <!--</span>-->
                  <!--<span v-if="shareUser.wechat">-->
                    <!--<el-icon><ChatDotRound /></el-icon>-->
                    <!--{{ shareUser.wechat }}-->
                  <!--</span>-->
                  <!--<span v-if="shareUser.email">-->
                    <!--<el-icon><Message /></el-icon>-->
                    <!--{{ shareUser.email }}-->
                  <!--</span>-->
                <!--</div>-->
              <!--</div>-->
            <!--</div>-->
          <!--</div>-->

          <!-- 岗位图片展示 -->
          <div class="job-images" v-if="currentJob.images && currentJob.images.length > 0">
              <h3>岗位图片</h3>
              <div class="image-gallery">
                  <el-carousel
                          :interval="4000"
                          type="card"
                          height="300px"
                          v-if="currentJob.images.length > 1"
                  >
                      <el-carousel-item v-for="(image, index) in currentJob.images" :key="index">
                          <div class="carousel-image" @click="previewImage(image, currentJob.images)">
                              <img :src="image.url" :alt="`岗位图片${index + 1}`" />
                          </div>
                      </el-carousel-item>
                  </el-carousel>
                  <div class="single-image" v-else @click="previewImage(currentJob.images[0], currentJob.images)">
                      <img :src="currentJob.images[0].url" :alt="'岗位图片'" />
                  </div>
              </div>
          </div>

          <!-- 岗位视频展示 -->
          <div class="job-videos" v-if="currentJob.videos && currentJob.videos.length > 0">
              <h3>岗位视频</h3>
              <div class="video-gallery">
                  <div
                          v-for="(video, index) in currentJob.videos"
                          :key="index"
                          class="video-item"
                  >
                      <h4>{{ video.name || `视频${index + 1}` }}</h4>
                      <video
                              :src="video.url"
                              controls
                              preload="metadata"
                              class="video-player"
                      >
                          您的浏览器不支持视频播放
                      </video>
                  </div>
              </div>
          </div>

          <!-- 相关文件展示 -->
          <div class="job-files" v-if="currentJob.files && currentJob.files.length > 0">
              <h3>相关文件</h3>
              <div class="file-list">
                  <div
                          v-for="(file, index) in currentJob.files"
                          :key="index"
                          class="file-item"
                  >
                      <!--<div class="file-icon">-->
                          <!--<el-icon><Document /></el-icon>-->
                      <!--</div>-->
                      <div class="file-info">
                          <div class="file-name">{{ file.name }}</div>
                          <div class="file-size">{{ formatFileSize(file.size) }}</div>
                      </div>
                      <div class="file-actions">
                          <el-button
                                  type="primary"
                                  size="small"
                                  @click="downloadFile(file)"
                          >
                              <el-icon><Download /></el-icon>
                              下载
                          </el-button>
                          <!--<el-button-->
                                  <!--size="small"-->
                                  <!--@click="previewFileHandler(file)"-->
                          <!--&gt;-->
                              <!--<el-icon><View /></el-icon>-->
                              <!--预览-->
                          <!--</el-button>-->
                      </div>
                  </div>
              </div>
          </div>

          <div class="job-detail-body">
          <div class="job-detail-section">
            <h3>工作详情</h3>
            <div class="detail-grid">
              <div class="detail-item">
                <el-icon><Location /></el-icon>
                <span><strong>工作地点：</strong>{{ currentJob.location || '暂无信息' }}</span>
              </div>
              <div class="detail-item">
                <el-icon><Money /></el-icon>
                <span><strong>薪资待遇：</strong>{{ currentJob.salary || currentJob.expectedSalary || '薪资面议' }}</span>
              </div>
              <div class="detail-item">
                <el-icon><User /></el-icon>
                <span><strong>经验要求：</strong>{{ currentJob.experience || currentJob.experienceRequirement || '经验不限' }}</span>
              </div>
              <div class="detail-item">
                <el-icon><Calendar /></el-icon>
                <span><strong>工作时间：</strong>{{ currentJob.workTime || currentJob.workingHours || '工作时间面议' }}</span>
              </div>
            </div>
          </div>
          
          <div class="job-detail-section">
            <h3>工作描述</h3>
            <div class="job-description-full">
              <p>{{ currentJob.jobDescription || currentJob.fullDescription || currentJob.description || '暂无工作描述' }}</p>
            </div>
          </div>
          
          <div class="job-detail-section">
            <h3>任职要求</h3>
            <ul class="requirements-list">
              <li v-for="requirement in (currentJob.requirementList || currentJob.jobRequirements || ['暂无具体要求'])" :key="requirement">
                {{ requirement }}
              </li>
            </ul>
          </div>
          
          <div class="job-detail-section">
            <h3>福利待遇</h3>
            <div class="benefits-grid">
              <div v-for="benefit in (currentJob.benefitList || currentJob.jobBenefits || ['具体福利面议'])" :key="benefit">
                <el-icon><Check /></el-icon>
                <span>{{ benefit }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="job-detail-actions">
          <el-button type="primary" size="large" @click="applyJob(currentJob)">
            {{ $t('jobs.apply') }}
          </el-button>
          <el-button size="large" @click="shareJob(currentJob)">
            分享岗位
          </el-button>
          <el-button size="large" @click="closeJobDetail">
            关闭
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 申请表单对话框 -->
    <el-dialog 
      v-model="applyFormVisible" 
      title="工作申请"
      width="60%"
      :before-close="closeApplyForm"
    >
      <el-form 
        ref="applyFormRef" 
        :model="applyForm" 
        :rules="applyFormRules" 
        label-width="120px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="applyForm.name" placeholder="请输入您的姓名" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="applyForm.phone" placeholder="请输入您的手机号" />
        </el-form-item>
        
        <el-form-item label="微信号" prop="wechat">
          <el-input v-model="applyForm.wechat" placeholder="请输入您的微信号" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="applyForm.email" placeholder="请输入您的邮箱" />
        </el-form-item>
        
        <el-form-item label="工作经验" prop="experience">
          <el-select v-model="applyForm.experience" placeholder="请选择工作经验" style="width: 100%">
            <el-option label="应届毕业生" value="应届毕业生" />
            <el-option label="1年以下" value="1年以下" />
            <el-option label="1-3年" value="1-3年" />
            <el-option label="3-5年" value="3-5年" />
            <el-option label="5年以上" value="5年以上" />
          </el-select>
        </el-form-item>
        
        <!--<el-form-item label="学历" prop="education">-->
          <!--<el-select v-model="applyForm.education" placeholder="请选择学历" style="width: 100%">-->
            <!--<el-option label="高中及以下" value="高中及以下" />-->
            <!--<el-option label="大专" value="大专" />-->
            <!--<el-option label="本科" value="本科" />-->
            <!--<el-option label="硕士" value="硕士" />-->
            <!--<el-option label="博士" value="博士" />-->
          <!--</el-select>-->
        <!--</el-form-item>-->
        
        <el-form-item label="期望薪资" prop="expectedSalary">
          <el-input v-model="applyForm.expectedSalary" placeholder="请输入期望薪资" />
        </el-form-item>
        
        <!--<el-form-item label="求职意向" prop="intention">-->
          <!--<el-input-->
            <!--v-model="applyForm.intention"-->
            <!--type="textarea"-->
            <!--:rows="3"-->
            <!--placeholder="请描述您的求职意向、技能特长等"-->
          <!--/>-->
        <!--</el-form-item>-->
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeApplyForm">取消</el-button>
          <el-button type="primary" @click="submitApplication">
            提交申请
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分享对话框 -->
    <el-dialog v-model="shareDialogVisible" title="分享岗位信息" width="500px">
      <div class="share-content">
        <div class="share-info">
          <h4>{{ currentJob?.jobTitle || currentJob?.title }}</h4>
          <p>{{ currentJob?.companyName || currentJob?.company?.name }} | {{ currentJob?.location || '地点待定' }} | {{ currentJob?.salary || currentJob?.expectedSalary || '薪资面议' }}</p>
        </div>
        
        <div class="share-link">
          <el-input
            :value="shareLink"
            readonly
            class="share-input"
          >
            <template #append>
              <el-button @click="copyShareLink">复制链接</el-button>
            </template>
          </el-input>
        </div>
        
        <div class="share-options">
          <el-button @click="shareToWechat" type="success" block>
            分享到微信
          </el-button>
          <el-button @click="shareToQQ" type="primary" block>
            分享到QQ
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Location, 
  Money, 
  User, 
  Calendar,
  Check
} from '@element-plus/icons-vue'
import { 
  getJobsList, 
  getJobDetail, 
  createJob, 
  updateJob, 
  deleteJob, 
  updateJobStatus, 
  batchDeleteJobs,
  uploadFiles,
  submitJobApplication,
  getShareUserInfo
} from '@/api/system'

const { t } = useI18n()
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const imageObj = computed(() => userStore.imageObj)

// 轮播图数据处理 - 参照Home.vue的firstImages实现
const sixImages = computed(() => {
  const raw = imageObj?.value?.sixUrl
  if (!raw) {
    return ['/src/assets/index/unnamed.png']
  }
  // 支持字符串数组或逗号分隔字符串
  let list = Array.isArray(raw) ? raw : String(raw).split(',')
  list = list.map(s => String(s).trim()).filter(Boolean)
  const resolved = list.map(url => {
    if (/^https?:\/\//i.test(url)) return url
    return (import.meta.env.VITE_BASE_URL || '') + url
  })
  return resolved.length ? resolved : ['/src/assets/index/unnamed.png']
})

const sixImagesKey = computed(() => sixImages.value.join('|'))

// 轮播图点击事件处理
const handleHeaderImageClick = (index, url) => {
  // 这里可以根据业务进行跳转或埋点
  // 先占位实现点击事件
  // console.log('clicked header image:', index, url)
}

// 兼容相对地址
const resolveUrl =(url)=> {
  if (!url) return ''
  if (/^https?:\/\//i.test(url)) return url
  return (import.meta.env.VITE_BASE_URL || '') + url
}


// 响应式数据
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(12)
const jobDetailVisible = ref(false)
const applyFormVisible = ref(false)
const currentJob = ref(null)
const applyFormRef = ref(null)
const loading = ref(false)
const totalJobs = ref(0)
const jobs = ref([])
const shareDialogVisible = ref(false)
const shareLink = ref('')

// 热门搜索标签 - 参照rb项目
const hotTags = [
  '食品加工', '餐饮服务', '护理服务', '农业', 
  '汽车维修', '建筑', '制造业', '物流运输'
]

// 申请表单
const applyForm = ref({
  name: '',
  phone: '',
  wechat: '',
  email: '',
  experience: '',
//  education: '',
  expectedSalary: '',
//  intention: ''
})

// 分享者信息
const shareUser = ref(null)
const shareUserId = ref(null)

// 表单验证规则
const applyFormRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  wechat: [
    { required: true, message: '请输入微信号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  experience: [
    { required: true, message: '请选择工作经验', trigger: 'change' }
  ],
//  education: [
//    { required: true, message: '请选择学历', trigger: 'change' }
//  ],
  expectedSalary: [
    { required: true, message: '请输入期望薪资', trigger: 'blur' }
  ],
//  intention: [
//    { required: true, message: '请填写求职意向', trigger: 'blur' }
//  ]
}

// 获取岗位列表 - 参照rb项目简化查询参数
const fetchJobs = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 如果有搜索关键词，添加到参数中
    if (searchKeyword.value.trim()) {
      params.keyword = searchKeyword.value.trim()
    }
    
    const response = await getJobsList(params)
    if (response.code === 200) {
      jobs.value = response.rows || []
      totalJobs.value = response.total || 0
    } else {
      ElMessage.error(response.msg || '获取岗位列表失败')
    }
  } catch (error) {
    console.error('获取岗位列表失败:', error)
    ElMessage.error('获取岗位列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取岗位详情
const fetchJobDetail = async (jobId) => {
  try {
    const response = await getJobDetail(jobId)
    if (response.code === 200) {

      if(response.data.images && response.data.images.length>0){
        response.data.images = JSON.parse(response.data.images)
      }
      if(response.data.files && response.data.files.length>0){
        response.data.files = JSON.parse(response.data.files)
      }
      if(response.data.videos && response.data.videos.length>0){
        response.data.videos = JSON.parse(response.data.videos)
      }
      return response.data
    } else {
      ElMessage.error(response.msg || '获取岗位详情失败')
      return null
    }
  } catch (error) {
    console.error('获取岗位详情失败:', error)
    ElMessage.error('获取岗位详情失败，请稍后重试')
    return null
  }
}

// 计算属性 - 参照rb项目简化，直接使用API返回的数据
const filteredJobs = computed(() => {
  return jobs.value
})

// 移除这个计算属性，因为我们现在从API获取总数

// 方法
const getTagType = (category) => {
  const typeMap = {
    '食品加工': 'primary',
    '餐饮服务': 'success',
    '护理服务': 'warning',
    '农业': 'info',
    '汽车维修': 'danger',
    '建筑': '',
    '制造业': 'primary',
    '物流运输': 'success',
    '清洁服务': 'warning'
  }
  return typeMap[category] || 'info'
}

// 搜索功能 - 参照rb项目
const handleSearch = async () => {
  // 重置分页
  currentPage.value = 1
  
  // 执行搜索
  await fetchJobs()
  
//  if (searchKeyword.value.trim()) {
//    ElMessage.success(`搜索"${searchKeyword.value}"完成，找到${jobs.value.length}个岗位`)
//  }
}

// 监听搜索关键词变化，实现实时搜索（可选）
watch(searchKeyword, (newVal, oldVal) => {
  // 如果用户清空了搜索框，自动刷新列表
  if (oldVal && !newVal) {
    handleSearch()
  }
}, { deep: true })

const filterJobs = () => {
  currentPage.value = 1
  fetchJobs()
}

const viewJobDetail = async (job) => {
  try {
    // 获取完整的岗位详情
    const jobDetail = await fetchJobDetail(job.positionId)
    if (jobDetail) {
      currentJob.value = jobDetail
      jobDetailVisible.value = true
      
      // 检查URL中是否有分享者ID
      const urlParams = new URLSearchParams(window.location.search)
      const urlShareUserId = urlParams.get('shareUserId')
      
      if (urlShareUserId) {
        shareUserId.value = urlShareUserId
        // 获取分享者信息
//        try {
//          const shareUserResponse = await getShareUserInfo(urlShareUserId)
//          if (shareUserResponse.code === 200) {
//            shareUser.value = shareUserResponse.data
//          }
//        } catch (error) {
//          console.error('获取分享者信息失败:', error)
//        }
      }
    }
    } catch (error) {
    console.error('获取岗位详情失败:', error)
  }
}

const closeJobDetail = () => {
  jobDetailVisible.value = false
  currentJob.value = null
  shareUser.value = null
//  shareUserId.value = null
}

const applyJob = (job) => {
  currentJob.value = job
  applyFormVisible.value = true
}

const closeApplyForm = () => {
  applyFormVisible.value = false
//  currentJob.value = null
  shareUser.value = null
//  shareUserId.value = null
  applyForm.value = {
    name: '',
    phone: '',
    wechat: '',
    email: '',
    experience: '',
//    education: '',
    expectedSalary: '',
//    intention: ''
  }
}

// 简历上传功能已移除，使用rb项目的简化字段

const submitApplication = async () => {
  if (!applyFormRef.value) return
  
  try {
    await applyFormRef.value.validate()
    
    // 上传简历文件
//    let resumeUrl = ''
//    if (applyForm.value.resume) {
//      try {
//        const uploadResponse = await uploadFiles([applyForm.value.resume.raw], 'resume')
//        if (uploadResponse.code === 200) {
//          resumeUrl = uploadResponse.data[0] || ''
//        }
//      } catch (error) {
//        console.error('简历上传失败:', error)
//        ElMessage.warning('简历上传失败，但申请仍可提交')
//      }
//    }
    
    // 构建申请数据
    const applicationData = {
      id: Date.now(),
      jobId: currentJob.value.positionId,
      shareUserId: shareUserId.value, // 添加分享者ID
      customerName: applyForm.value.name,
      phone: applyForm.value.phone,
      wechat: applyForm.value.wechat,
      email: applyForm.value.email,
      experience: applyForm.value.experience,
      expectedSalary: applyForm.value.expectedSalary,
      registerTime: new Date().toISOString(),
      status: 'pending',

//      jobTitle: currentJob.value.jobTitle || currentJob.value.title || '未知职位',
//      education: applyForm.value.education,
//      intention: applyForm.value.intention,
    }
    
    // 调用申请接口
    const response = await submitJobApplication(applicationData)
    if (response.code === 200) {
      ElMessage.success('申请提交成功！我们会尽快联系您。')
      closeApplyForm()
    } else {
      ElMessage.error(response.msg || '申请提交失败')
    }
    
  } catch (error) {
    ElMessage.error('请检查表单信息是否正确')
  }
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchJobs()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchJobs()
}

// 预览文件
const previewFileHandler = (file) => {
  // 如果是图片文件，使用图片预览
  if (isImageFile(file.name)) {
    previewImage({ url: file.url }, [{ url: file.url }])
  } else {
    // 其他文件直接下载或在新窗口打开
    window.open(file.url, '_blank')
  }
}
// 下载文件
const downloadFile = (file) => {
  const link = document.createElement('a')
  link.href = file.url
  link.download = file.name
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('文件下载已开始')
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '未知大小'
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]
}

// 分享岗位
const shareJob = (job) => {
  currentJob.value = job
  const userInfo = localStorage.getItem('user') && typeof localStorage.getItem('user') == 'string'? JSON.parse(localStorage.getItem('user')) : {}
  shareUserId.value = userInfo?.userId
  shareDialogVisible.value = true
  shareLink.value = `${window.location.origin}/jobs?jobId=${job.positionId}&shareUserId=${userInfo?.userId || 1}`
}

// 从列表分享岗位
const shareJobFromList = (job) => {
  currentJob.value = job
  const userInfo = localStorage.getItem('user') && typeof localStorage.getItem('user') == 'string'? JSON.parse(localStorage.getItem('user')) : {}
  shareUserId.value = userInfo?.userId
  shareDialogVisible.value = true
  shareLink.value = `${window.location.origin}/jobs?jobId=${job.positionId}&shareUserId=${userInfo?.userId || 1}`
}

// 复制分享链接
const copyShareLink = async () => {
  try {
    await navigator.clipboard.writeText(shareLink.value)
    ElMessage.success('链接已复制到剪贴板！')
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage.error('复制失败，请手动复制')
  }
}

// 分享到微信
const shareToWechat = async () => {
  try {
    await navigator.clipboard.writeText(shareLink.value)
//    ElMessage.success('已复制微信分享链接！')
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage.error('复制失败，请手动复制')
  }
}

// 分享到QQ
const shareToQQ = async () => {
  try {
    await navigator.clipboard.writeText(shareLink.value)
//    ElMessage.success('已复制QQ分享链接！')
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage.error('复制失败，请手动复制')
  }
}

onMounted(() => {
  // 初始化数据
  fetchJobs()
  
  // 检查URL参数，如果有jobId和shareUserId，自动显示岗位详情
  const urlParams = new URLSearchParams(window.location.search)
  const jobId = urlParams.get('jobId')
  const shareUserId = urlParams.get('shareUserId')
  
  if (jobId) {
    // 延迟执行，确保岗位列表已加载
    setTimeout(async () => {
      const job = jobs.value.find(j => j.positionId == jobId)
      if (job) {
        await viewJobDetail(job)
      }
    }, 1000)
  }
})
</script>

<style scoped>
.jobs {
  min-height: 100vh;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 页面头部 */
.page-header {
  position: relative;
  height: 300px;
  display: flex;
  align-items: center;
  color: white;
  overflow: hidden;
}

.header-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.el-carousel {
  height: 100%;
}

.header-bg-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.header-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(44, 62, 80, 0.3), rgba(52, 73, 94, 0.3));
}

.header-content {
  position: relative;
  z-index: 2;
  width: 80%;
    margin: auto;
  text-align: center;
}

.header-content h1 {
  font-size: 3rem;
  font-weight: bold;
  margin-bottom: 15px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}

.header-content p {
  font-size: 1.2rem;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

/* 筛选器区域 - 参照rb项目样式 */
.filters-section {
  background: #f8f9fa;
  padding: 30px 0;
  border-bottom: 1px solid #e9ecef;
}

.filters {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.search-box {
  display: flex;
  gap: 15px;
  align-items: center;
  justify-content: center;
  max-width: 600px;
  margin: 0 auto;
}

.search-input {
  flex: 1;
}

.search-btn {
  min-width: 100px;
}

.search-tags {
  display: flex;
  align-items: center;
  gap: 10px;
  justify-content: center;
  flex-wrap: wrap;
  margin-top: 20px;
}

.tag-label {
  color: #666;
  font-size: 14px;
}

.hot-tag {
  cursor: pointer;
  transition: all 0.3s ease;
}

.hot-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

/* 工作区域 */
.jobs-section {
  padding: 40px 0;
  background: white;
}

.jobs-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 30px;
  margin-bottom: 40px;
}

.job-card {
  background: white;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
}

.job-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.job-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.job-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.job-card:hover .job-image img {
  transform: scale(1.05);
}

.job-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.job-card:hover .job-overlay {
  opacity: 1;
}

.job-info {
  padding: 20px;
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.job-header h3 {
  font-size: 1.2rem;
  color: #2c3e50;
  margin: 0;
  flex: 1;
  margin-right: 15px;
}

.job-company {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 0.9rem;
  color: #666;
}

.company-logo {
  width: 30px;
  height: 15px;
  object-fit: contain;
}

.job-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 15px;
}

.job-details > div {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 0.9rem;
  color: #666;
}

.job-tags {
  display: flex;
  gap: 5px;
  margin-bottom: 15px;
}

.job-description {
  margin-bottom: 15px;
}

.job-description p {
  color: #666;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.job-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.job-actions .el-button {
  flex: 1;
  min-width: 80px;
}

/* 工作详情对话框 */
.job-detail-content {
  max-height: 70vh;
  overflow-y: auto;
}

.job-detail-header {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e9ecef;
}

.job-detail-image {
  width: 200px;
  height: 150px;
  object-fit: cover;
  border-radius: 10px;
}

.job-detail-info h2 {
  margin: 0 0 15px 0;
  color: #2c3e50;
}

.company-info {
  display: flex;
  gap: 15px;
  align-items: center;
}

.company-logo-large {
  width: 60px;
  height: 30px;
  object-fit: contain;
}

.company-info h4 {
  margin: 0 0 5px 0;
  color: #2c3e50;
}

.company-info p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
}

.job-detail-body {
  margin-bottom: 30px;
}

.job-detail-section {
  margin-bottom: 25px;
}

.job-detail-section h3 {
  color: #2c3e50;
  margin-bottom: 15px;
  font-size: 1.2rem;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #666;
}

.job-description-full p {
  color: #666;
  line-height: 1.6;
}

.requirements-list {
  list-style: none;
  padding: 0;
}

.requirements-list li {
  padding: 8px 0;
  color: #666;
  border-bottom: 1px solid #f0f0f0;
}

.requirements-list li:before {
  content: "•";
  color: #409EFF;
  font-weight: bold;
  margin-right: 10px;
}

.benefits-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 10px;
}

.benefit-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
}

.benefit-item .el-icon {
  color: #67C23A;
}

.job-detail-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #e9ecef;
}

/* 分享者信息样式 */
.share-info-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e9ecef;
}

.share-info-section h3 {
  color: #2c3e50;
  margin-bottom: 15px;
  font-size: 1.2rem;
}

.share-user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.share-user-avatar {
  width: 60px;
  height: 60px;
  background-color: #409EFF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 2rem;
}

.share-user-details h4 {
  margin: 0 0 5px 0;
  color: #2c3e50;
}

.share-user-details p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
}

.share-user-contact {
  display: flex;
  gap: 15px;
  margin-top: 10px;
}

.share-user-contact span {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
  font-size: 0.9rem;
}

.share-user-contact .el-icon {
  font-size: 1.1rem;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

/* 分享对话框样式 */
.share-content {
  padding: 20px 0;
}

.share-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.share-info h4 {
  color: #2c3e50;
  margin: 0 0 8px 0;
  font-size: 1.1rem;
}

.share-info p {
  color: #666;
  margin: 0;
  font-size: 0.9rem;
}

.share-link {
  margin-bottom: 20px;
}

.share-input {
  width: 100%;
}

.share-options {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.share-options .el-button {
  height: 40px;
  font-size: 14px;
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content h1 {
    font-size: 2rem;
  }
  
  .header-content p {
    font-size: 1rem;
  }
  
  .jobs-grid {
    grid-template-columns: 1fr;
  }
  
  .job-header {
    flex-direction: column;
    gap: 10px;
  }
  
  .job-detail-header {
    flex-direction: column;
  }
  
  .job-detail-image {
    width: 100%;
    height: 200px;
  }
  
  .detail-grid {
    grid-template-columns: 1fr;
  }
  
  .benefits-grid {
    grid-template-columns: 1fr;
  }
}
</style>